import React, { useCallback } from 'react';
import { LogoutOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin, message } from 'antd';
import { history, useModel } from 'umi';
import { stringify } from 'querystring';
import HeaderDropdown from './HeaderDropdown';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';
import { LOGIN_PATH, NORMAL_CODE } from '@/constants';


export type GlobalHeaderRightProps = {
  menu?: boolean;
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  //数据模型
  const authModel = useModel('auth.auth', (model) => ({
    logout: model.logout,
  }));

  /**
   * 退出登录，并且将当前的 url 保存
   */
  const logout = async () => {
    const res = await authModel.logout({});
    if (res.code !== NORMAL_CODE) {
      message.error(res.msg);
    }
    const { query = {}, search, pathname } = history.location;
    const { redirect } = query;
    // Note: There may be security issues, please note
    if (window.location.pathname !== LOGIN_PATH && !redirect) {
      history.replace({
        pathname: LOGIN_PATH,
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };
  /**
   * 点击菜单
   */
  const onMenuClick = useCallback((event: MenuInfo) => {
    const { key } = event;
    if (key === 'logout') {
      logout();
      return;
    }
    history.push(`/account/${key}`);
  }, []);

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState || !initialState.authData || !initialState.authData.nickname) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu
      className={styles.menu}
      selectedKeys={[]}
      onClick={onMenuClick}
      items={[
        {
          key: 'logout',
          icon: <LogoutOutlined />,
          label: `退出登录`,
        },
        // {menu && (
        //   <Menu.Item key="center">
        //     <UserOutlined />
        //     个人中心
        //   </Menu.Item>
        // )}
        // {menu && (
        //   <Menu.Item key="settings">
        //     <SettingOutlined />
        //     个人设置
        //   </Menu.Item>
        // )}
        // {menu && <Menu.Divider />}
      ]}
    ></Menu>
  );
  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar
          size="small"
          className={styles.avatar}
          src={initialState.authData.avatar}
          alt="avatar"
        />
        <span className={`${styles.name} anticon`}>{initialState.authData.nickname}</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
